package com.example.taobaounion.presenter.impl;

import androidx.annotation.NonNull;

import com.example.taobaounion.model.Api;
import com.example.taobaounion.model.domain.Categories;
import com.example.taobaounion.presenter.IHomePresenter;
import com.example.taobaounion.utils.LogUtils;
import com.example.taobaounion.utils.RetrofitUtils;
import com.example.taobaounion.view.callback.IHomeCallback;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class HomePresenter implements IHomePresenter {
    private static final String TAG = "HomePresenter";

    private IHomeCallback mCallBack;

    @Override
    public void getCategories() {

        if (mCallBack != null) {
            mCallBack.onLoading();
        }

        Retrofit retrofit = RetrofitUtils.getInstance().getRetrofit();

        Api api = retrofit.create(Api.class);

        Call<Categories> task = api.getCategories();

        task.enqueue(new Callback<Categories>() {
            @Override
            public void onResponse(@NonNull Call<Categories> call, @NonNull Response<Categories> response) {
                // 结果
                int code = response.code();

                LogUtils.d(TAG, "result code --- >" + code);

                if (code == HttpURLConnection.HTTP_OK) {
                    Categories categories = response.body();

                    assert categories != null;
//                    LogUtils.d(TAG, categories.toString());

                    if (mCallBack != null) {
                        if (categories.getData().size() == 0) {
                            mCallBack.onEmpty();
                        } else {
                            mCallBack.onCategoriesLoaded(categories);
                        }
                    }
                } else {

                    LogUtils.i(TAG, "请求失败。。。");

                    if (mCallBack != null) {
                        mCallBack.onNetworkError();
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<Categories> call, @NonNull Throwable t) {
                // 失败
                LogUtils.e(TAG, "请求错误");

                if (mCallBack != null) {
                    mCallBack.onNetworkError();
                }
            }
        });
    }

    @Override
    public void registerViewCallback(IHomeCallback callback) {
        this.mCallBack = callback;
    }

    @Override
    public void unRegisterViewCallback(IHomeCallback callback) {
        mCallBack = null;
    }
}
